# $Id: crontab.py 7557b5d4d82b 2012/12/02 09:07:16 pgurumur $
# Copyright (c) 2009 Prabhu Gurumurthy  <pgurumur@gmail.com>
# 
# Permission to use, copy, modify, and distribute this software for any
# purpose with or without fee is hereby granted, provided that the above
# copyright notice and this permission notice appear in all copies.
#
# THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
# WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
# MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
# ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
# WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
# ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
# OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
#
__author__ = "$Author: pgurumur $"

from datetime import datetime, timedelta
import time
import threading

from djanet.lib import stdlib
from djanet.lib import log

# Some utility classes / functions first
class AllMatch(set):
    """Universal set - match everything"""
    def __contains__(self, item): return True

allMatch = AllMatch()

def conv2set(obj):  # Allow single integer to be provided
    if isinstance(obj, (int,long)):
        return set([obj])  # Single item
    if not isinstance(obj, set):
        obj = set(obj)

    return obj

# The actual Event class
class Event(object):
   def __init__(self, action, min = allMatch, hour = allMatch, day = allMatch,
         month = allMatch, dow = allMatch, args = (), kwargs = {}):

      self._log = log.StreamLog(stdlib.my_name(self))
      self.mins = conv2set(min)
      self.hours = conv2set(hour)
      self.days = conv2set(day)
      self.months = conv2set(month)
      self.dow = conv2set(dow)
      self.action = action
      self.args = args
      self.kwargs = kwargs

   def matchtime(self, tm):
      """Return True if this event should trigger at the specified datetime"""
      return ((tm.minute in self.mins) and
            (tm.hour in self.hours) and
            (tm.day in self.days) and
            (tm.month in self.months) and
            (tm.weekday() in self.dow))

   def run(self, tm):
      if self.matchtime(tm):
         actstr = ""
         try:
            actstr = str(self.action)
         except:
            pass

         try:
            self.action(*self.args, **self.kwargs)
         except:
            self._log("%s failed to execute properly", actstr)

class CronTab(object):
   def __init__(self, verbose = False, *events):
      self._log = log.StreamLog(stdlib.my_name(self))
      self.events = events
      self.verbose = False

   def run(self):
      it=datetime(*datetime.now().timetuple()[:5])
      while True:
         if self.verbose:
            self._log("running...")

         for ev in self.events:
            ev.run(it)

         it += timedelta(minutes=1)
         while datetime.now() < it:
            time.sleep((it - datetime.now()).seconds)


class crond(threading.Thread):
   def __init__(self, *events):
      super(crond, self).__init__(name = stdlib.my_name(self))
      self.cron = CronTab(False, *events)

   def run(self):
      self.cron.run()

